import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import morgan from 'morgan';
import path from 'path';
import { fileService } from './services/fileService';
import agentRoutes from './routes/agents';
import tagRoutes from './routes/tags';
import classifyRoutes from './routes/classifies';
import { 
  errorHandler, 
  notFoundHandler, 
  requestLogger, 
  corsHandler 
} from './middleware/errorHandler';
import { getConfig, isDevelopment } from './config';
import { ApiResponse } from './types/agent';

/**
 * 创建Express应用实例
 */
function createApp(): express.Application {
  const app = express();
  const config = getConfig();

  // 基础中间件配置
  app.use(helmet({
    contentSecurityPolicy: {
      directives: {
        defaultSrc: ["'self'"],
        styleSrc: ["'self'", "'unsafe-inline'"],
        scriptSrc: ["'self'"],
        imgSrc: ["'self'", "data:", "https:"],
        connectSrc: ["'self'"],
        fontSrc: ["'self'"],
        objectSrc: ["'none'"],
        mediaSrc: ["'self'"],
        frameSrc: ["'none'"]
      }
    },
    crossOriginEmbedderPolicy: false
  }));

  // CORS配置
  app.use(cors({
    origin: function (origin, callback) {
      // 在开发环境允许所有来源
      if (isDevelopment()) {
        callback(null, true);
        return;
      }
      
      // 生产环境使用配置文件中的白名单
      const allowedOrigins = config.cors.origin;
      
      if (!origin || allowedOrigins.includes(origin)) {
        callback(null, true);
      } else {
        callback(new Error('Not allowed by CORS'));
      }
    },
    credentials: true,
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
    allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With']
  }));

  // 处理预检请求
  app.use(corsHandler);

  // 请求解析中间件
  app.use(express.json({ limit: '10mb' }));
  app.use(express.urlencoded({ extended: true, limit: '10mb' }));

  // 日志中间件
  if (isDevelopment()) {
    app.use(morgan('dev'));
    app.use(requestLogger);
  } else {
    app.use(morgan('combined'));
  }

  // 静态文件服务（如果需要）
  app.use('/static', express.static(path.join(__dirname, '../public')));

  // 健康检查端点
  app.get('/health', (req, res) => {
    const response: ApiResponse = {
      success: true,
      data: {
        status: 'OK',
        timestamp: new Date().toISOString(),
        version: process.env.npm_package_version || '1.0.0',
        environment: process.env.NODE_ENV || 'development',
        uptime: process.uptime(),
        memory: process.memoryUsage(),
        pid: process.pid
      }
    };
    res.json(response);
  });

  // 测试路由 - 用于调试
  app.get('/api/test', (req, res) => {
    console.log('[DEBUG] Test route accessed');
    res.json({ success: true, message: 'Test route working' });
  });

  // API routes with debug logging (注册在具体路由之前)
  app.use('/api/agents', (req, res, next) => {
    console.log(`[DEBUG] Agents route: ${req.method} ${req.path}`);
    next();
  }, agentRoutes);
  
  app.use('/api/tags', (req, res, next) => {
    console.log(`[DEBUG] Tags route: ${req.method} ${req.path}`);
    next();
  }, tagRoutes);
  
  app.use('/api/classifies', (req, res, next) => {
    console.log(`[DEBUG] Classifies route: ${req.method} ${req.path}`);
    next();
  }, classifyRoutes);

  // API信息端点（放在具体路由之后）
  app.get('/api', (req, res) => {
    const response: ApiResponse = {
      success: true,
      data: {
        name: 'Agent Share Platform API',
        version: '1.0.0',
        description: 'RESTful API for managing AI agents',
        endpoints: {
          agents: '/api/agents',
          tags: '/api/tags',
          classifies: '/api/classifies',
          health: '/health',
          docs: '/api/docs'
        },
        timestamp: new Date().toISOString()
      }
    };
    res.json(response);
  });

  // API文档端点（简单版本）
  app.get('/api/docs', (req, res) => {
    const docs = {
      openapi: '3.0.0',
      info: {
        title: 'Agent Share Platform API',
        version: '1.0.0',
        description: 'API for managing AI agents'
      },
      servers: [
        {
          url: `http://localhost:${config.port}`,
          description: 'Development server'
        }
      ],
      paths: {
        '/api/agents': {
          get: {
            summary: 'Get all agents',
            parameters: [
              { name: 'page', in: 'query', schema: { type: 'integer' } },
              { name: 'limit', in: 'query', schema: { type: 'integer' } },
              { name: 'search', in: 'query', schema: { type: 'string' } },
              { name: 'category', in: 'query', schema: { type: 'string' } }
            ]
          },
          post: {
            summary: 'Create new agent',
            requestBody: {
              required: true,
              content: {
                'application/json': {
                  schema: {
                    type: 'object',
                    required: ['name', 'description'],
                    properties: {
                      name: { type: 'string' },
                      description: { type: 'string' },
                      category: { type: 'string' },
                      tags: { type: 'array', items: { type: 'string' } },
                      config: { type: 'object' },
                      prompt: { type: 'string' },
                      avatar: { type: 'string' },
                      isPublic: { type: 'boolean' }
                    }
                  }
                }
              }
            }
          }
        },
        '/api/agents/{id}': {
          get: { summary: 'Get agent by ID' },
          put: { summary: 'Update agent' },
          delete: { summary: 'Delete agent' }
        },
        '/api/agents/stats': {
          get: { summary: 'Get statistics' }
        },
        '/api/agents/export': {
          get: { summary: 'Export agents data' }
        },
        '/api/agents/import': {
          post: { summary: 'Import agents data' }
        }
      }
    };
    
    res.json(docs);
  });

  // 404处理
  app.use(notFoundHandler);

  // 全局错误处理
  app.use(errorHandler);

  return app;
}

/**
 * 启动服务器
 */
export async function startServer(): Promise<void> {
  try {
    const config = getConfig();
    
    // 初始化文件服务
    console.log('Initializing file service...');
    await fileService.initialize();
    console.log('File service initialized successfully');
    
    // 创建应用
    const app = createApp();
    
    // 启动服务器
    const server = app.listen(config.port, () => {
      console.log(`\n🚀 Server is running!`);
      console.log(`📍 Environment: ${process.env.NODE_ENV || 'development'}`);
      console.log(`🌐 Server URL: http://localhost:${config.port}`);
      console.log(`📚 API Docs: http://localhost:${config.port}/api/docs`);
      console.log(`💚 Health Check: http://localhost:${config.port}/health`);
      console.log(`📊 API Info: http://localhost:${config.port}/api`);
      console.log(`\n📁 Data Directory: ${config.dataDir}`);
      console.log(`📁 Logs Directory: ${config.logsDir}`);
      console.log(`\n🔧 Available endpoints:`);
      console.log(`   GET    /api/agents           - List all agents`);
      console.log(`   POST   /api/agents           - Create new agent`);
      console.log(`   GET    /api/agents/:id       - Get agent by ID`);
      console.log(`   PUT    /api/agents/:id       - Update agent`);
      console.log(`   DELETE /api/agents/:id       - Delete agent`);
      console.log(`   GET    /api/agents/stats     - Get statistics`);
      console.log(`   GET    /api/agents/export    - Export data`);
      console.log(`   POST   /api/agents/import    - Import data`);
      console.log(`   GET    /api/tags             - List all tags`);
      console.log(`   POST   /api/tags             - Create new tag`);
      console.log(`   GET    /api/tags/:id         - Get tag by ID`);
      console.log(`   PUT    /api/tags/:id         - Update tag`);
      console.log(`   DELETE /api/tags/:id         - Delete tag`);
      console.log(`   GET    /api/classifies       - List all classifies`);
      console.log(`   POST   /api/classifies       - Create new classify`);
      console.log(`   GET    /api/classifies/:id   - Get classify by ID`);
      console.log(`   PUT    /api/classifies/:id   - Update classify`);
      console.log(`   DELETE /api/classifies/:id   - Delete classify`);
      console.log(`\n✨ Ready to serve requests!\n`);
    });
    
    // 优雅关闭处理
    const gracefulShutdown = (signal: string) => {
      console.log(`\n📡 Received ${signal}. Starting graceful shutdown...`);
      
      server.close(async (err) => {
        if (err) {
          console.error('❌ Error during server shutdown:', err);
          process.exit(1);
        }
        
        try {
          // 这里可以添加清理逻辑，比如关闭数据库连接等
          console.log('✅ Server closed successfully');
          console.log('👋 Goodbye!');
          process.exit(0);
        } catch (cleanupError) {
          console.error('❌ Error during cleanup:', cleanupError);
          process.exit(1);
        }
      });
      
      // 强制退出超时
      setTimeout(() => {
        console.error('⏰ Forced shutdown due to timeout');
        process.exit(1);
      }, 10000);
    };
    
    // 监听退出信号
    process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
    process.on('SIGINT', () => gracefulShutdown('SIGINT'));
    
    // 监听未捕获的异常
    process.on('uncaughtException', (error) => {
      console.error('❌ Uncaught Exception:', error);
      gracefulShutdown('uncaughtException');
    });
    
    process.on('unhandledRejection', (reason, promise) => {
      console.error('❌ Unhandled Rejection at:', promise, 'reason:', reason);
      gracefulShutdown('unhandledRejection');
    });
    
  } catch (error) {
    console.error('❌ Failed to start server:', error);
    process.exit(1);
  }
}

// 如果直接运行此文件，则启动服务器
if (require.main === module) {
  startServer();
}

export { createApp };
export default createApp;